package com.jdpay.hermes.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @version 1.0
 * @Author zhangxiaoli5
 * @Description AES对称加密工具类
 * @Date 2019/8/9 9:42
 **/
public class AESUtils {

    public AESUtils() {
    }

    public static byte[] encrypt(String data, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        return encrypt(data.getBytes(Charset.forName("UTF-8")), password);
    }

    public static byte[] encrypt(byte[] data, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKeySpec = buildSecretKeySpec(password);
        Cipher cipher = Cipher.getInstance(secretKeySpec.getAlgorithm());
        cipher.init(1, secretKeySpec);
        return cipher.doFinal(data);
    }

    public static String decrypt(byte[] data, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKeySpec = buildSecretKeySpec(password);
        Cipher cipher = Cipher.getInstance(secretKeySpec.getAlgorithm());
        cipher.init(2, secretKeySpec);
        return new String(cipher.doFinal(data), Charset.forName("UTF-8"));
    }

    private static SecretKeySpec buildSecretKeySpec(String password) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AESUtil");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes(Charset.forName("UTF-8")));
        keyGenerator.init(128, random);
        SecretKey secretKey = keyGenerator.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), "AESUtil");
    }

}
